<template>
    <div>
        <ly-dialog v-model="dialogVisible" :title="dialogTitle" width="560px" :before-close="handleClose">
            <el-form :inline="false" :model="formData" :rules="rules" ref="rulesForm" label-position="right" label-width="auto" class="form-store">
                <el-form-item label="父级菜单：" prop="parent">
                    <el-cascader
                            style="width: 100%"
                            :key="isResourceShow"
                            :show-all-levels="false"
                            :options="options"
                            v-model="formData.parent"
                            @change="handleChange"
                            :props="{expandTrigger:'hover', checkStrictly: true, label:'name', value:'id'}"
                            placeholder="请选择父级菜单"
                            clearable></el-cascader>
                </el-form-item>
                <el-form-item label="菜单名称：" prop="name">
                    <el-input v-model.trim="formData.name" ></el-input>
                </el-form-item>
                <el-form-item label="侧边栏可见：" prop="visible">
                    <el-radio-group v-model="formData.visible" >
                        <el-radio :label="true">是</el-radio>
                        <el-radio :label="false">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="创建按钮权限：" prop="isautopm">
                    <el-radio-group v-model="formData.isautopm" >
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="0">否</el-radio>
                    </el-radio-group>
                    <span style="font-size: 12px;color: red;">*【否】表示创建一个目录</span>
                </el-form-item>
                <el-form-item label="图标：" prop="icon">
<!--                    <el-input v-model.trim="formData.icon" ></el-input>-->
                    <l-y-choose-icons v-model="formData.icon"></l-y-choose-icons>
<!--                    <el-autocomplete-->
<!--                            v-model.trim="formData.icon"-->
<!--                            :fetch-suggestions="querySearch"-->
<!--                            :trigger-on-focus="false"-->
<!--                            clearable-->
<!--                            style="width: 100%"-->
<!--                            @select="handleSelect"-->
<!--                            popper-append-to-body-->
<!--                            placeholder="请输入icon">-->
<!--                        <template #default="{ item }">-->
<!--                            <div style="display: flex;align-items: center">-->
<!--                                <el-icon :size="16">-->
<!--                                    <component :is="item.value"></component>-->
<!--                                </el-icon>-->
<!--                                <div style="margin-left: 5px;">{{ item.value }}</div>-->
<!--                            </div>-->
<!--                        </template>-->
<!--                    </el-autocomplete>-->
                </el-form-item>
                <el-form-item label="排序：" prop="order_num">
                    <el-input-number v-model="formData.order_num" :min="0" :max="9999"></el-input-number>
                </el-form-item>
                <el-form-item label="路由地址：" prop="path">
                    <el-input v-model.trim="formData.path" ></el-input>
                    <el-alert title="请填写xxx.vue中的name或文件名作为路由地址" type="info" show-icon/>
                </el-form-item>
                <el-form-item label="状态：" prop="status">
                    <el-radio-group v-model="formData.status" style="width: 300px">
                        <el-radio :label="true">启用</el-radio>
                        <el-radio :label="false">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>

            </el-form>
            <template #footer>
                <el-button @click="handleClose" :loading="loadingSave">取消</el-button>
                <el-button type="primary" @click="submitData" :loading="loadingSave">确定</el-button>
            </template>
        </ly-dialog>
    </div>
</template>

<script>
    import {apiSystemMenu,apiSystemMenuAdd,apiSystemMenuEdit,systemMenuTree} from '@/api/api'
    import XEUtils from "xe-utils";
    import {menuicons} from "@/utils/menuTree.js"
    import LyDialog from "@/components/dialog/dialog.vue";
    import LYChooseIcons from "@/components/icons/chooseIcons.vue";
    import {deepClone} from "@/utils/util";

    export default {
        components: {LYChooseIcons, LyDialog},
        emits: ['refreshData'],
        name: "addMenu",
        data() {
            return {
                menuicons:[],
                dialogVisible:false,
                loadingSave:false,
                dialogTitle:'',
                isResourceShow:0,
                formData:{
                    parent_id:'',
                    name:'',
                    visible:true,
                    icon:'',
                    status:true,
                    order_num:0,
                    path:'',
                    menuPermission:[],
                    isautopm:1,
                },
                inputVisible: false,
                inputValue: '',
                rules:{
                   /* parent: [
                        {required: true, message: '请选择父级菜单',trigger: 'blur'}
                    ],*/
                    name: [
                        {required: true, message: '请输入菜单名称',trigger: 'blur'}
                    ],
                    visible: [
                        {required: true, message: '请选择侧边栏是否可见',trigger: 'blur'}
                    ],
                    order_num: [
                        {required: true, message: '请输入排序',trigger: 'blur'}
                    ],
                    // icon: [
                    //     {required: true, message: '请填充图标',trigger: 'blur'}
                    // ],
                    status: [
                        {required: true, message: '请选择状态',trigger: 'blur'}
                    ],
                    // web_path: [
                    //     {required: true, message: '请输入路由地址',trigger: 'blur'}
                    // ],
                    isautopm: [
                        {required: true, message: '请选择是否自动创建按钮权限',trigger: 'blur'}
                    ],
                },
                options: []
            }
        },
        mounted() {
            this.menuicons = menuicons
        },
        methods:{
            handleCloseTag(tag) {
                this.formData.menuPermission.splice(this.formData.menuPermission.indexOf(tag), 1);
            },

            showInput() {
                this.inputVisible = true;
                this.$nextTick(_ => {
                    this.$refs.saveTagInput.$refs.input.focus();
                });
            },

            handleInputConfirm() {
                let inputValue = this.inputValue;
                if (inputValue) {
                    this.formData.menuPermission.push(inputValue);
                }
                this.inputVisible = false;
                this.inputValue = '';
            },
            handleSelect(item){
                // console.log(item)
            },
            querySearch(queryString, cb) {
                var menuicons = this.menuicons;
                var results = queryString ? menuicons.filter(this.createFilter(queryString)) : menuicons;
                // 调用 callback 返回建议列表的数据
                cb(results);
            },
            createFilter(queryString) {
                return (menuicons) => {
                  return (menuicons.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
                };
            },

            handleChange(e) {
              //console.log(e,'e----')
                // this.parent = e[e.length-1]
            },
            handleClose() {
                this.dialogVisible=false
                this.loadingSave=false
                this.formData = {
                    parent_id:'',
                    name:'',
                    visible:true,
                    icon:'',
                    status:true,
                    order_num:0,
                    path:'',
                    menuPermission:[],
                    isautopm:1,
                    parent: []
                }
                console.log('✅ 关闭对话框，重置表单数据')
            },
            addMenuFn(item,flag) {
                this.dialogVisible=true
                this.dialogTitle=flag

                //解决Cannot read property 'level' of null问题
                this.options=[]
                this.isResourceShow=0
                
                // 获取菜单树，并在完成后设置表单数据
                this.getsystemMenuTree().then(() => {
                    if(item){
                        // 编辑时，复制数据并进行字段映射
                        this.formData = {
                            id: item.id,
                            parent_id: item.parent_id || '',
                            name: item.name || '',
                            visible: item.visible !== undefined ? item.visible : true,
                            icon: item.icon || '',
                            status: item.status !== undefined ? item.status : true,
                            order_num: item.order_num || 0,
                            path: item.path || '',
                            menuPermission: item.menuPermission || [],
                            isautopm: item.isautopm !== undefined ? item.isautopm : 1,
                        }
                        
                        console.log('🔍 编辑菜单:', item.name, '父级ID:', item.parent_id)
                        
                        // 处理父级菜单的显示 - 构建级联选择器需要的完整路径数组
                        this.$nextTick(() => {
                            if(item.parent_id) {
                                // 有父级菜单，构建完整的父级路径
                                const parentPath = this.buildParentPath(item.parent_id)
                                this.formData.parent = parentPath
                                console.log('✅ 设置父级菜单路径:', parentPath)
                            } else {
                                // 没有父级菜单，选中根节点
                                this.formData.parent = ['-1']
                                console.log('✅ 设置为根节点:', ['-1'])
                            }
                            // 强制更新级联选择器的key
                            this.isResourceShow++
                        })
                    } else {
                        // 新增时重置为默认值
                        this.formData = {
                            parent_id:'',
                            name:'',
                            visible:true,
                            icon:'',
                            status:true,
                            order_num:0,
                            path:'',
                            menuPermission:[],
                            isautopm:1,
                        }
                        this.formData.parent = []
                        console.log('✅ 新增菜单，重置表单')
                    }
                }).catch(error => {
                    console.error('❌ 获取菜单树失败，无法初始化父级菜单:', error)
                    this.$message.error('获取菜单数据失败，请重试')
                })
            },
            
            // 构建父级菜单的完整路径（从根节点到目标父级菜单）
            buildParentPath(parentId) {
                if (!parentId) return ['-1']
                
                // 扁平化菜单数据，便于查找
                const flatMenus = this.flattenMenuOptions(this.options)
                const path = []
                
                // 递归构建路径
                const buildPath = (currentId) => {
                    const menu = flatMenus.find(m => m.id == currentId)
                    if (menu) {
                        if (menu.parentId && menu.parentId !== '-1') {
                            buildPath(menu.parentId)
                        }
                        path.push(currentId)
                    }
                }
                
                // 总是从根节点开始
                path.push('-1')
                buildPath(parentId)
                
                return path
            },
            
            // 扁平化菜单选项数据
            flattenMenuOptions(menuOptions) {
                let result = []
                
                const flatten = (menus, parentId = null) => {
                    menus.forEach(menu => {
                        result.push({
                            id: menu.id,
                            name: menu.name,
                            parentId: parentId
                        })
                        if (menu.children && menu.children.length > 0) {
                            flatten(menu.children, menu.id)
                        }
                    })
                }
                
                flatten(menuOptions)
                return result
            },
            submitData() {
                console.log('🔍 提交菜单数据:', this.formData)
                this.$refs['rulesForm'].validate(obj=>{
                    if(obj) {
                        let param = {
                            ...this.formData
                        }
                        
                        // 处理父级菜单ID - 从级联选择器数组中提取
                        if (this.formData.parent && this.formData.parent.length > 0) {
                            const lastParent = this.formData.parent[this.formData.parent.length - 1]
                            // 如果选择的是根节点(-1)，则parent_id为null
                            param.parent_id = lastParent === '-1' ? null : lastParent
                        } else {
                            param.parent_id = null
                        }
                        
                        console.log('🔍 处理后的parent_id:', param.parent_id)
                        
                        // 删除parent字段，使用parent_id
                        delete param.parent
                        
                        this.loadingSave=true
                        if(this.dialogTitle=="新增"){
                            console.log('🔍 新增菜单参数:', param)
                            apiSystemMenuAdd(param).then(res=>{
                                this.loadingSave=false
                                if(res.code == 200) {
                                    this.$message.success(res.message)
                                    this.handleClose()
                                    this.$emit('refreshData')
                                    console.log('✅ 新增菜单成功')
                                } else {
                                    this.$message.warning(res.message)
                                    console.error('❌ 新增菜单失败:', res.message)
                                }
                            }).catch(error => {
                                this.loadingSave=false
                                console.error('❌ 新增菜单请求失败:', error)
                                this.$message.error('新增菜单失败，请重试')
                            })
                        }else{
                            if(!param.id) {
                                this.loadingSave=false
                                this.$message.error('菜单ID不存在，无法编辑')
                                return
                            }
                            
                            console.log('🔍 编辑菜单参数:', param)
                            apiSystemMenuEdit(param.id, param).then(res=>{
                                this.loadingSave=false
                                if(res.code == 200) {
                                    this.$message.success(res.message)
                                    this.handleClose()
                                    this.$emit('refreshData')
                                    console.log('✅ 编辑菜单成功')
                                } else {
                                    this.$message.warning(res.message || '编辑失败')
                                    console.error('❌ 编辑菜单失败:', res.message)
                                }
                            }).catch(error => {
                                this.loadingSave=false
                                console.error('❌ 编辑菜单请求失败:', error)
                                if(error.response && error.response.status === 404) {
                                    this.$message.error(`菜单不存在 (ID: ${param.id})，请刷新页面重试`)
                                } else {
                                    this.$message.error('编辑菜单失败，请重试')
                                }
                            })
                        }

                    }
                })
            },
            getsystemMenuTree() {
                return apiSystemMenu({tree: true}).then(res=>{
                    ++this.isResourceShow
                    if(res.code == 200) {
                        let menu = [{
                            id: '-1',
                            name:'根节点',
                            children: res.data
                            }]
                        // 后端已经返回树形结构，直接使用
                        this.options = menu
                        console.log('🔍 菜单树数据加载完成:', menu)
                        return res
                    } else {
                        this.$message.warning(res.message)
                        throw new Error(res.message)
                    }
                }).catch(error => {
                    console.error('获取菜单树失败:', error)
                    this.$message.error('获取菜单树失败，请重试')
                    throw error
                })
            }
        }
    }
</script>
<style lang="scss" scoped>
    .el-tag + .el-tag {
        margin-left: 10px;
    }
    .button-new-tag {
        margin-left: 10px;
        height: 32px;
        line-height: 30px;
        padding-top: 0;
        padding-bottom: 0;
    }
    .input-new-tag {
        width: 90px;
        margin-left: 10px;
        vertical-align: bottom;
    }
</style>


